package com.jiang.demo.depotstable.dds.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.jiang.demo.depotstable.dds.datasource.DDS;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jiangzhe
 * @create 2021/5/11 14:15
 */
@Slf4j
@Configuration
public class DDSConfig {
    @Value("${spring.datasource.store.url}")
    private String storeDBUrl;
    @Value("${spring.datasource.store.username}")
    private String storeDBUser;
    @Value("${spring.datasource.store.password}")
    private String storeDBPassword;
    @Value("${spring.datasource.store.driver-class-name}")
    private String storeDBDriverName;

    // 为避免在 xxApplication 中通过 annotation.Value("") 方式获取不到，直接将配置数据以静态变量的形式保存。todo 后期看怎么优化从配置文件获取
    public static String productDBUrl = "jdbc:mysql://127.0.0.1:?port?/product_db?characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull";
    public static String productDBUser = "root";
    public static String productDBPassword = "123456";
    public static String productDBDriverName = "com.mysql.cj.jdbc.Driver";

    @Bean("dds")
    public DDS dds() {
        DDS dds = DDS.getInstance();

        DruidDataSource storeDS = new DruidDataSource();
        storeDS.setUrl(storeDBUrl);
        storeDS.setUsername(storeDBUser);
        storeDS.setPassword(storeDBPassword);
        storeDS.setDriverClassName(storeDBDriverName);

        Map<Object,Object> map = new HashMap<>();
        map.put("store-db", storeDS);
        dds.setTargetDataSources(map);
        dds.setDefaultTargetDataSource(storeDS);

        return dds;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dds") DataSource dds) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dds);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    
}
